package com.fch.server.service;

import com.fch.server.domain.Teacher;
import com.fch.server.domain.TeacherExample;
import com.fch.server.dto.TeacherDto;
import com.fch.server.dto.PageDto;
import com.fch.server.mapper.TeacherMapper;
import com.fch.server.util.CopyUtil;
import com.fch.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: fangchuhao
 **/
@Service
public class TeacherService {
    private static final Logger LOG = LoggerFactory.getLogger(TeacherService.class);

    @Resource
    private TeacherMapper teacherMapper;

    /**
     * 列表查询
     */
    public void list(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        TeacherExample teacherExample = new TeacherExample();
        List<Teacher> teachers = teacherMapper.selectByExample(teacherExample);
        PageInfo<Teacher> teacherPageInfo = new PageInfo<>(teachers);
        pageDto.setTotal(teacherPageInfo.getTotal());
        List<TeacherDto> teacherDtos = CopyUtil.copyList(teachers, TeacherDto.class);
        pageDto.setList(teacherDtos);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    public void save(TeacherDto teacherDto) {
        Teacher teacher = CopyUtil.copy(teacherDto,Teacher.class);
        if (StringUtils.isEmpty(teacher.getId())) {
            insert(teacher);
        }else {
            update(teacher);
        }
    }

    /**
     * 新增
     */
    private void insert(Teacher teacher) {
        teacher.setId(UuidUtil.getShortUuid());
        teacherMapper.insert(teacher);
    }

    /**
     * 更新
     */
    private void update(Teacher teacher) {
        teacherMapper.updateByPrimaryKey(teacher);
    }

    /**
     * 删除
     */
    public void delete(String id) {
        teacherMapper.deleteByPrimaryKey(id);
    }

    public List<TeacherDto> all() {
        TeacherExample teacherExample = new TeacherExample();
        List<Teacher> teachers = teacherMapper.selectByExample(teacherExample);
        return CopyUtil.copyList(teachers, TeacherDto.class);
    }

    public TeacherDto findById(String id) {
        Teacher teacher = teacherMapper.selectByPrimaryKey(id);
        return CopyUtil.copy(teacher, TeacherDto.class);
    }
}
